<template>
  <div class="search">
    <div class="search-container">
      <!-- 输入框 + 查询按钮 -->
      <el-input v-model="searchForm.keyword" placeholder="输入仓库编号/仓库名称/" clearable
        style="width: 200px; margin-right: 10px;" />
      <el-button type="primary" @click="searchWarehouse">查询</el-button>

      <!-- 复选框 + 职员管理链接 -->
      <el-checkbox v-model="searchForm.status" @change="handleCheck" style="margin-left: 20px;">显示禁用仓库</el-checkbox>

      <!-- 操作按钮组 -->
      <div class="search-right" v-if="!info.outButton">
        <el-button type="primary" @click="openAddDialog">新增</el-button>
        <el-button plain>导入</el-button>
        <el-button plain>导出</el-button>
        <el-button plain @click="refresh">刷新</el-button>
      </div>
    </div>

    <el-dialog v-model="dialogFormVisible" :title="dialog === 'add' ? '新增仓库' : '编辑仓库'" width="500">
      <el-form :model="form" ref="formRef">
        <el-form-item label="仓库编号" :label-width="formLabelWidth">
          <el-input v-model="form.code" autocomplete="off" />
        </el-form-item>
        <el-form-item label="仓库名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="仓管人员" :label-width="formLabelWidth">
          <el-select v-model="form.staffId" placeholder="请选择" style="width: 100%;">
            <el-option v-for="staff in warehouseManagerList" :key="staff.id" :label="staff.name" :value="staff.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitWarehouse">
            确认
          </el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <el-table :data="tableData" border style="width: 100%" stripe @selection-change="handleSelection" ref="tableRef">
    <el-table-column v-if="info.selection" type="selection" width="55" />
    <el-table-column v-if="info.no" type="index" label="序号" width="180" />
    <el-table-column v-if="info.name" prop="name" label="仓库名称" width="180" />
    <el-table-column v-if="info.staffId" prop="staffId" label="仓管人员">
      <template #default="scope">
        <el-tag>{{ warehouseManagerList.find(staff => staff.id === scope.row.staffId)?.name || '未分配' }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column v-if="info.code" prop="code" label="仓库编号" />
    <el-table-column v-if="info.status" prop="status" label="状态">
      <template #default="scope">
        <el-switch :model-value="scope.row.status" :active-value="1" :inactive-value="0"
          @change="() => handleStatusChange(scope.row)" />
      </template>
    </el-table-column>
    <el-table-column label="操作" v-if="info.op">
      <template #default="scope">
        <el-button type="primary" icon="Edit" @click="openEditDialog(scope.row)" />
        <el-button type="primary" icon="Delete" @click="delHouse(scope.row.id)" />
      </template>
    </el-table-column>
  </el-table><br />

  <!-- 分页 -->
  <div class="demo-pagination-block" style="float: right;">
    <el-pagination v-model:current-page="pageInfo.pageNum" v-model:page-size="pageInfo.pageSize"
      :page-sizes="[5, 10, 15, 20]" :background="true" layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref, defineProps, defineExpose, onMounted } from 'vue'
import axios from 'axios'

const tableRef = ref()
const formRef = ref()
const loading = ref(false)

const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const dialog = ref('add')

const selectedArray = ref([])

const pageInfo = reactive({
  total: 0,
  pageSize: 10,
  pageNum: 1
})

//xyy改造nw的仓库搜索组件
defineProps({
  info: {
    type: Object,
    default: () => ({
      selection: true,
      no: true,
      name: true,
      code: true,
      staffId: true,
      status: true,
      op: true,
      outButton: false
    })
  }
})

// 选择处理
const handleSelection = (selection) => {
  selectedArray.value = selection
}

// 清空选择
const clearSelected = () => {
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
}

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: 1
})

// 搜索
const searchWarehouse = () => {
  pageInfo.pageNum = 1
  getWarehouseList()
}

// 仓库数据
const tableData = ref([])

// 仓库分页
const getWarehouseList = async () => {
  try {
    loading.value = true
    const res = await axios.get('/api/basic/warehouse/warehouseByPage', {
      params: {
        pageNum: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
        ...searchForm
      }
    })

    if (res.data.code === 5200) {
      tableData.value = res.data.pageInfo.list
      pageInfo.total = res.data.pageInfo.total
      pageInfo.pageNum = res.data.pageInfo.pageNum
    } else {
      ElMessage.error('获取仓库列表失败')

    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('加载失败')
    //假数据，当宁武电脑服务没启动时
    tableData.value = [{
      id: 1,
      code: 'WH001',
      name: '华东中心仓',
      staffId: 101,
      status: 1
    },
    {
      id: 2,
      code: 'WH002',
      name: '华南配送仓',
      staffId: 102,
      status: 0
    },
    {
      id: 3,
      code: 'WH003',
      name: '华北前置仓',
      staffId: 103,
      status: 1
    },]
    pageInfo.total = 3
    pageInfo.pageNum = 1
  } finally {
    loading.value = false
  }
}

// 查询角色为仓管的员工
const warehouseManagerList = ref([])

const getStaffList = async () => {
  try {
    const res = await axios.get('/api/basic/warehouse/allWarehouseManager')
    if (res.data.code === 5200) {
      warehouseManagerList.value = res.data.warehouseManagerList
    } else {
      ElMessage.error('获取仓库员工列表失败')
    }
  } catch (error) {
    console.error('获取仓库员工失败:', error)
    ElMessage.error('加载失败')
  }
}

// 多选框：显示禁用数据
const handleCheck = (checked) => {
  searchForm.status = checked ? null : 1
  getWarehouseList()
}

const form = reactive({
  name: '',
  code: '',
  staffId: '',
})

// 新增对话框
const openAddDialog = async () => {
  await getStaffList()
  form.name = ''
  form.code = ''
  form.staffId = ''
  dialog.value = 'add'
  dialogFormVisible.value = true
}

// 修改对话框
const openEditDialog = async (row) => {
  await getStaffList()
  form.id = row.id
  form.name = row.name
  form.code = row.code
  form.staffId = row.staffId
  dialog.value = 'edit'
  dialogFormVisible.value = true
}

// 提交
const submitWarehouse = async () => {
  if (!form.code) {
    ElMessage.error('编号不能为空')
    return;
  }
  if (!form.name) {
    ElMessage.error('名称不能为空')
    return;
  }

  let res = null

  if (dialog.value === 'add') {
    res = await axios.post('/api/basic/warehouse/addWarehouse', form)
  } else {
    res = await axios.post('/api/basic/warehouse/updateWarehouse', form)
  }

  if (res.data.code === 5200) {
    ElMessage.success(res.data.msg)
    await getWarehouseList()
  } else {
    ElMessage.error(res.data.msg)
  }
  dialogFormVisible.value = false
}



// 页容量发生改变
const handleSizeChange = (val) => {
  pageInfo.pageSize = val
  pageInfo.pageNum = 1
  getWarehouseList()
}

// 页码发生改变
const handleCurrentChange = (val) => {
  pageInfo.pageNum = val
  getWarehouseList()
}


// 删除单个
const delHouse = async (id) => {
  try {

    await ElMessageBox.confirm('确定删除此仓库吗？此操作不可恢复')

    const res = await axios.post('/api/basic/warehouse/deleteWarehouse', null, { params: { id } })

    if (res.data.code === 5200) {
      ElMessage.success(res.data.msg)
      getWarehouseList()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    if (error === 'cancel' || error?.message === 'cancel') {
      console.log('用户取消了删除操作')
    } else {
      ElMessage.error('删除操作出现错误: ' + (error.response?.data?.msg || error.message))
    }
  }
}

// 状态切换
const handleStatusChange = async (row) => {
  const originalStatus = row.status;
  try {
    const res = await axios.post('/api/basic/warehouse/updateWarehouseStatus', null, {
      params: { id: row.id }
    });
    if (res.data.code !== 5200) {
      row.status = originalStatus;
      ElMessage.error('状态更新失败');
    } else {
      ElMessage.success('状态更新成功');
    }
  } catch (error) {
    row.status = originalStatus;
    ElMessage.error('网络错误，请重试');
  } finally {
    await getWarehouseList();
  }
};

// 刷新
const refresh = () => {
  searchForm.keyword = ''
  searchForm.showDisabled = false
  pageInfo.pageNum = 1
  getWarehouseList()
}

// 暴露方法给父组件
defineExpose({
  selectedArray,
  clearSelected,
})

onMounted(() => {
  getWarehouseList()
  getStaffList()
})

</script>

<style scoped>
/* 搜索表单 */
.search-container {
  display: flex;
  align-items: center;
  gap: 10px;
  /* 控制元素之间的间距 */
  padding: 10px 0;
  overflow-x: auto;
  /* 如果内容超出屏幕宽度，允许水平滚动*/
}

/* 确保操作按钮组与左侧元素对齐 */
.search-right {
  margin-left: auto;
  /* 将右侧按钮组推到最右边 */
  display: flex;
  gap: 10px;
}

/* 复选框与链接样式 */
.search-container .el-checkbox {
  margin-left: auto;
  /* 自动边距将复选框推到中间 */
}


.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>